//
//  LXJComposeView.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/4.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit
import SnapKit
import pop

/// 发微博视图

class LXJComposeView: UIView {
    // MARK: 控件的懒加载
    /// 遮罩图片
    fileprivate lazy var backgroundMaskImgView: UIImageView = {
        let img = UIImageView()
        /// 设置截屏图片,并对其进行模糊化处理
        img.image = self.getScreenshotImage().applyLightEffect()
        return img
    }()
    
    /// 标语图片
    fileprivate lazy var sloganMaskImgView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    /// 摁扭的模型数组
    fileprivate lazy var buttonsInfoModelArr: [LXJComposeWeiboButtonInfoModel] = [LXJComposeWeiboButtonInfoModel]()
    
    /// 摁扭数组
    fileprivate lazy var buttonsArr: [LXJComposeButton] = [LXJComposeButton]()
    
    ///  目标控制器
    var target: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 设置尺寸
        size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
        /// 添加子控件
        addSubview(backgroundMaskImgView)
        addSubview(sloganMaskImgView)
        
        /// 自动布局
        backgroundMaskImgView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        sloganMaskImgView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-150)
        }
        
        /// 获取摁扭的信息
        loadButtonInfo()
        
        /// 摁扭布局
        layoutChildButton()
        
        /// 执行摁扭的动画
        popAnimation(isUp: true)
    }
    
    // MARK: 加载 plis 文件 获取摁扭的信息
    fileprivate func loadButtonInfo() {
        /// 获取文件路径
        let path = Bundle.main.path(forResource: "tabbar_compose.plist", ofType: nil)
        /// 获取内容
        let dataArray = NSArray.init(contentsOfFile: path!)
        /// 数组转模型
        buttonsInfoModelArr = NSArray.yy_modelArray(with: LXJComposeWeiboButtonInfoModel.self, json: dataArray as Any) as! [LXJComposeWeiboButtonInfoModel]
        
        /// 添加子摁扭
        addChildButton()
    }
    
    // MARK: 添加子摁扭
    fileprivate func addChildButton() {
        for (index,buttonModel) in buttonsInfoModelArr.enumerated() {
            let but = LXJComposeButton(title: buttonModel.title!, imageName: buttonModel.icon, target: self, action: #selector(composeWeibo(sender:)))
            /// 设置摁扭的 tag 值
            but.tag = index
            /// 添加到摁扭数组中
            buttonsArr.append(but)
            addSubview(but)
        }
    }
    
    // MARK: 调整摁扭的陈列位置
    fileprivate func layoutChildButton() {
        /// 设置摁扭的大小
        let buttonWidth: CGFloat = 71
        let buttonHeight: CGFloat = 121
        
        /// 设置摁扭的间距
        let margin = (width - buttonWidth * 4) / 5
        
        for (index, button) in buttonsArr.enumerated() {
            /// 获取行索引
            let rowIndex: CGFloat = CGFloat(index / 4)
            
            /// 获取列索引
            let colIndex: CGFloat = CGFloat(index % 4)
            
            /// 计算摁扭的 x 坐标
            button.x = margin * (colIndex + 1) + buttonWidth * colIndex
            /// 计算摁扭的 y 坐标
            button.y = margin * rowIndex + buttonHeight * rowIndex + ScreenHeight
            /// 设置摁扭的尺寸
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
        }
    }
    
    // MARK: 摁扭的动画效果
    fileprivate func popAnimation(isUp: Bool) {
        /// 向下
        if isUp == false {
            ///  如果是向下的动画,数组翻转
            buttonsArr = buttonsArr.reversed()
        }
        
        ///  遍历按钮创建pop动画
        for (i, button) in buttonsArr.enumerated() {
            ///  创建pop动画
            let pop = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            ///  抖动幅度,值越大抖动幅度就越大
            pop?.springBounciness = 10
            ///  弹簧速度,速度越快,动画结束越快
            pop?.springSpeed = 10
            ///  动画开始时间的间隔,CACurrentMediaTime() 是系统的绝对时间
            pop?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            if isUp {
                ///  动画执行的目的地
                pop?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            } else {
                ///  动画执行的目的地
                pop?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
            ///  执行动画
            button.pop_add(pop, forKey: nil)
        }
    }
    
    
    /// 点击屏幕视图消失
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        ///  执行向下的动画
        popAnimation(isUp: false)
        ///  延时.25秒执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            self.removeFromSuperview()
        }
    }
    
    /// 截取图片
    fileprivate func getScreenshotImage() -> UIImage {
        /// 获取 Window
        let window = UIApplication.shared.keyWindow
        /// 开启图片上下文
        UIGraphicsBeginImageContext((window?.size)!)
        /// 截屏
        window?.drawHierarchy(in: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight), afterScreenUpdates: false)
        /// 从上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        /// 关闭图片上下文
        UIGraphicsEndImageContext()
        /// 将得到的图片进行返回
        return image!
    }
    
    /// 发表 微博的8个功能
    @objc fileprivate func composeWeibo(sender: UIButton) -> Void {
        ///  通过tag获取模型
        let compose = buttonsInfoModelArr[sender.tag]
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.buttonsArr {
                /// 修改摁扭的透明度
                button.alpha = 0.5
                /// 摁扭大小的变化
                if button == sender {
                    ///  放大1.5倍
                    button.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
                } else {
                    ///  缩小0.5倍
                    button.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
                }
            }
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: {
                for button in self.buttonsArr {
                    /// 还原摁扭的透明度
                    button.alpha = 1
                    ///  重置摁扭的transform
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                ///  弹出控制器
                
                ///  通过类名字符串转成class类型
                let classType = NSClassFromString(compose.className!) as! UIViewController.Type
                /// 通过class类型获取实例
                let vc = classType.init()
                /// 创建导航控制器
                let nav = LXJNavigationController(rootViewController: vc)
                ///  莫泰新的视图控制器
                self.target?.present(nav, animated: true, completion: {
                    ///  移除罩层
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    ///  显示罩层视图
    func showMaskView(target: UIViewController) {
        ///  保存目标控制器
        self.target = target
        ///  把视图添加到TabbarController的view上
        self.target?.view.addSubview(self)
    }
}
